/**
 * 验证手机号码
 * @param {string} phone - 要验证的手机号码
 * @returns {boolean} - 验证结果，true 表示有效，false 表示无效
 */
export function validatePhone(phone) {
  // 中国大陆手机号码正则，支持 13、14、15、16、17、18、19 开头的号码
  const phoneReg = /^1[3-9]\d{9}$/;
  return phoneReg.test(phone);
}

// 也可以添加其他验证方法，比如邮箱验证、身份证验证等
/**
 * 验证邮箱
 * @param {string} email - 要验证的邮箱
 * @returns {boolean} - 验证结果
 */
export function validateEmail(email) {
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  return emailReg.test(email);
}

export function formatTimestamp(timestamp, format = 'YYYY-MM-DD') {
  if (!timestamp) {
    return '';
  }
  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  const replacements = {
    YYYY: year,
    MM: month,
    DD: day,
    hh: hours,
    mm: minutes,
    ss: seconds,
  };

  return format.replace(/YYYY|MM|DD|hh|mm|ss/g, (match) => replacements[match]);
}

// 计算坐标是否可服务

// 1. 经纬度转弧度
const toRadians = (degrees) => (degrees * Math.PI) / 180;

// 2. 计算两点间地表距离（米，Haversine公式）
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371000; // 地球半径（米）
  const φ1 = toRadians(lat1);
  const φ2 = toRadians(lat2);
  const Δφ = toRadians(lat2 - lat1);
  const Δλ = toRadians(lng2 - lng1);

  const a =
    Math.sin(Δφ / 2) ** 2 + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) ** 2;
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
};

// 3. 经纬度转平面直角坐标（以参考点为原点，米为单位）
const toPlaneCoords = (refLat, refLng, targetLat, targetLng) => {
  const x =
    calculateDistance(refLat, refLng, refLat, targetLng) *
    (targetLng > refLng ? 1 : -1);
  const y =
    calculateDistance(refLat, refLng, targetLat, refLng) *
    (targetLat > refLat ? 1 : -1);
  return { x, y };
};

// 4. 多边形/矩形判断（射线法）
const isPointInPolygon = (pointLat, pointLng, polygonPaths) => {
  let inside = false;
  const n = polygonPaths.length;

  for (let i = 0, j = n - 1; i < n; j = i++) {
    const xi = polygonPaths[i].lng,
      yi = polygonPaths[i].lat;
    const xj = polygonPaths[j].lng,
      yj = polygonPaths[j].lat;

    const intersect =
      yi > pointLat !== yj > pointLat &&
      pointLng < ((xj - xi) * (pointLat - yi)) / (yj - yi) + xi;

    if (intersect) inside = !inside;
  }
  return inside;
};

// 5. 圆形判断
const isPointInCircle = (pointLat, pointLng, circle) => {
  const { center, radius } = circle;
  const distance = calculateDistance(
    pointLat,
    pointLng,
    center.lat,
    center.lng,
  );
  return distance <= radius;
};

// 6. 矩形判断
const isPointInRectangle = (pointLat, pointLng, rectangle) => {
  const { center, width, height } = rectangle;
  const { x, y } = toPlaneCoords(center.lat, center.lng, pointLat, pointLng);
  return Math.abs(x) <= width / 2 && Math.abs(y) <= height / 2;
};

// 7. 椭圆判断
const isPointInEllipse = (pointLat, pointLng, ellipse) => {
  const { center, majorRadius, minorRadius } = ellipse;
  const { x, y } = toPlaneCoords(center.lat, center.lng, pointLat, pointLng);
  return (x / majorRadius) ** 2 + (y / minorRadius) ** 2 <= 1;
};

/**
 * 判断点是否在任意已绘制图形内
 * @param {number} lat - 待判断点纬度
 * @param {number} lng - 待判断点经度
 * @param {Object} savedGeometries - 所有图形数据（你的数据结构）
 * @returns {Object} { isInside: boolean, matchedGeometries: Array }
 */
export const isPointInAnyGeometry = (lat, lng, savedGeometries) => {
  const matched = [];

  // 遍历多边形
  if (savedGeometries.polygon && savedGeometries.polygon.length) {
    savedGeometries.polygon.forEach((geo) => {
      if (isPointInPolygon(lat, lng, geo.paths)) {
        matched.push({ type: 'polygon', geometry: geo });
      }
    });
  }

  // 遍历圆形
  if (savedGeometries.circle && savedGeometries.circle.length) {
    savedGeometries.circle.forEach((geo) => {
      if (
        isPointInCircle(lat, lng, { center: geo.center, radius: geo.radius })
      ) {
        matched.push({ type: 'circle', geometry: geo });
      }
    });
  }

  // 遍历矩形
  if (savedGeometries.rectangle && savedGeometries.rectangle.length) {
    savedGeometries.rectangle.forEach((geo) => {
      if (
        isPointInRectangle(lat, lng, {
          center: geo.center,
          width: geo.width,
          height: geo.height,
        })
      ) {
        matched.push({ type: 'rectangle', geometry: geo });
      }
    });
  }

  // 遍历椭圆
  if (savedGeometries.ellipse && savedGeometries.ellipse.length) {
    savedGeometries.ellipse.forEach((geo) => {
      if (
        isPointInEllipse(lat, lng, {
          center: geo.center,
          majorRadius: geo.majorRadius,
          minorRadius: geo.minorRadius,
        })
      ) {
        matched.push({ type: 'ellipse', geometry: geo });
      }
    });
  }

  return {
    isInside: matched.length > 0,
    matchedGeometries: matched,
  };
};
